/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Alquileres;
import entities.Operaciones;
import entities.Usuarios;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import javax.persistence.Query;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import renders.TipoAlquilerRender;

/**
 *
 * @author root
 */
public class BusquedaAlquiler extends JPanel {

    private static JFrame frame;
    private Usuarios usuario;
    private Alquileres alquiler;
    private Operaciones operacion;

    public BusquedaAlquiler(Usuarios usuario) {
        this.usuario = usuario;
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
    }

    public Query elegirQuery() {
        operacion = MovimientosCaja.getOperacion();
        switch (operacion.getOperacion()) {
            case "RESERVA":
                query = entityManager.createNamedQuery("Alquileres.findReservas");
                break;
            case "ALQUILER":
                query = entityManager.createNamedQuery("Alquileres.findAlquileresNoLiquidados");
                break;
            case "DEVOLUCION DE EFECTIVO":
                query = entityManager.createNamedQuery("Alquileres.findAlquileresConSaldoAFavor");
                break;
            default:
                query = entityManager.createNamedQuery("Alquileres.findAll");
                break;
        }
        return query;
    }

    private void cerrarVentana() {
        if (frame != null) {
            frame.dispose();
            frame = null;
        }
    }

    public static JFrame getFrame() {
        return frame;
    }

    private void seleccionarAlquiler() {
        int row = masterTable.getSelectedRow();
        int column = masterTable.getSelectedColumn();

        alquiler = list.get(masterTable.convertRowIndexToModel(row));
        try {
            MovimientosCaja.setearObservaciones(alquiler);
            cerrarVentana();
        } catch (Exception e) {
            // No cierro la ventana porque el dialogo fue abierto directamente
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : elegirQuery();
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        aceptarButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        masterTable.setColumnSelectionAllowed(true);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idAlquiler}"));
        columnBinding.setColumnName("Id Alquiler");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idUnidadAlojamiento}"));
        columnBinding.setColumnName("Id Unidad Alojamiento");
        columnBinding.setColumnClass(entities.UnidadesAlojamiento.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idCliente}"));
        columnBinding.setColumnName("Id Cliente");
        columnBinding.setColumnClass(entities.Clientes.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tipoAlquiler}"));
        columnBinding.setColumnName("Tipo Alquiler");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaArribo}"));
        columnBinding.setColumnName("Fecha Arribo");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaPartida}"));
        columnBinding.setColumnName("Fecha Partida");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${montoTotal}"));
        columnBinding.setColumnName("Monto Total");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${montoReserva}"));
        columnBinding.setColumnName("Monto Reserva");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cantidadPersonas}"));
        columnBinding.setColumnName("Cantidad Personas");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        masterTable.getColumnModel().getColumn(3).setCellRenderer(new TipoAlquilerRender());

        aceptarButton.setBackground(new java.awt.Color(1, 154, 210));
        aceptarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        aceptarButton.setForeground(new java.awt.Color(255, 255, 255));
        aceptarButton.setText("Aceptar");
        aceptarButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(aceptarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(370, 370, 370))
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 864, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(aceptarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == aceptarButton) {
                BusquedaAlquiler.this.aceptarButtonActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                BusquedaAlquiler.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        if (evt.getClickCount() == 2) {
            seleccionarAlquiler();
        }
    }//GEN-LAST:event_masterTableMouseClicked

    private void aceptarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarButtonActionPerformed
        if ((list.size() == 0) || (operacion.getOperacion() == "RETIRO DE EFECTIVO")) {
            cerrarVentana();
        } else {
            if (masterTable.getSelectedRow() == -1) {
                JOptionPane.showMessageDialog(null, "Seleccione un alquiler para continuar");
            } else {
                seleccionarAlquiler();
            }
        }
    }//GEN-LAST:event_aceptarButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptarButton;
    private javax.persistence.EntityManager entityManager;
    private java.util.List<entities.Alquileres> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.persistence.Query query;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public void main(Usuarios usuario) {
        final Usuarios usuarioActual = usuario;
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BusquedaAlquiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BusquedaAlquiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BusquedaAlquiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BusquedaAlquiler.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame = new JFrame();
                frame.setContentPane(new BusquedaAlquiler(usuarioActual));
                if (list.size() == 0){
                    JOptionPane.showMessageDialog(null, "No hay resultados para la operación seleccionada.");
                    cerrarVentana();
                }
                if (frame == null) {
                    return;
                }
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.setTitle("Busqueda de Alquileres   -   Movimientos de caja   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.pack();
                frame.setVisible(true);
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        frame.setVisible(false);
                        frame = null;
                    }
                });
            }
        });
    }
}